package com.wondersgroup.fjzlpt.gateway.filtes;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.wondersgroup.fjzlpt.gateway.filtes.exception.QuickZuulFilterException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

/**
 * 鉴权过滤器
 * 必须放在cert之后
 * Created by lion on 2017/6/18.
 */
public class QuickAuthClientFilter extends ZuulFilter {

    /*鉴权uri的后缀*/
    @Value("${gateway.authUriSuffix}")
    private String authUriSuffix;

    /**ant匹配方式*/
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String uri = ctx.getRequest().getRequestURI();
        if(ctx.get("certInfo") == null || !antPathMatcher.match(this.authUriSuffix, uri)){
            return false;
        }
        return true;
    }

    @Override
    public Object run() {
        RequestContext cxt = RequestContext.getCurrentContext();
        HttpServletRequest request = cxt.getRequest();
        String uri = request.getRequestURI();
        JSONObject certInfo = (JSONObject)RequestContext.getCurrentContext().get("certInfo");
        JSONObject roleInfo = certInfo.getJSONObject("roleInfo");
        JSONArray ary = roleInfo.getJSONArray("URLS");
        boolean isMatch = false;
        Iterator iter = ary.iterator();
        while(iter.hasNext()){
            String url = (String)iter.next();
            isMatch = this.antPathMatcher.match(url, uri);
            /*匹配上则不再匹配*/
            if(isMatch){
                break;
            }
        }
        if(!isMatch){
            throw new QuickZuulFilterException(QuickZuulFilterException.TYPE_UNAUTH, "访问未授权的资源");
        }
        return null;
    }
}
